package com.apex.aolonfitdemo.ui;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apex.aolonfit.AolonFitManager;
import com.apex.aolonfitdemo.R;
import com.apex.aolonfitdemo.databinding.ActivityHomeBinding;
import com.apex.ax_bluetooth.callback.GeneralCallback;
import com.apex.ax_bluetooth.core.EABleManager;
import com.apex.ax_bluetooth.enumeration.EABleConnectState;
import com.apex.ax_bluetooth.model.EABleBindInfo;
import com.cyber.bridge.module.bean.HardwareConfig;
import com.cyber.bridge.module.callback.OnCyberDataCallBack;
import com.cyber.bridge.module.listener.OnCyberBLEConnectStateListener;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity {
    ActivityHomeBinding activityHomeBinding;
    String deviceMac;
    private boolean isConnected;
    private ItemAdapter itemAdapter;
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x00) {
                //开始添加4.0不在设备配置的功能
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(HomeActivity.this);
                linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
                activityHomeBinding.functionList.setLayoutManager(linearLayoutManager);
                itemAdapter = new ItemAdapter((List<String>) msg.obj);
                activityHomeBinding.functionList.setAdapter(itemAdapter);
            } else if (msg.what == 0x01) {
                if (msg.arg1 == 0) {
                    isConnected = false;
                    activityHomeBinding.connectState.setText(getString(R.string.device_disconnect));
                } else if (msg.arg1 == 1) {
                    isConnected = false;
                    activityHomeBinding.connectState.setText(getString(R.string.connecting));
                } else {
                    isConnected = true;
                    activityHomeBinding.connectState.setText(getString(R.string.device_connected));
                    AolonFitManager.getInstance().queryHardwareConfig();
                   final   EABleBindInfo eaBleBindInfo = new EABleBindInfo();
                     eaBleBindInfo.setBind_mod(0);
                     eaBleBindInfo.setE_ops(EABleBindInfo.BindingOps.normal_begin);
                     eaBleBindInfo.setUser_id(System.currentTimeMillis() + "");
                     EABleManager.getInstance().setOpsBinding(eaBleBindInfo, new GeneralCallback() {
                    @Override public void result(boolean b, int i) {
                        if (b){
                           eaBleBindInfo.setE_ops(EABleBindInfo.BindingOps.end);
                           EABleManager.getInstance().setOpsBinding(eaBleBindInfo, new GeneralCallback() {
                               @Override
                               public void result(boolean b, int i) {

                               }

                               @Override
                               public void mutualFail(int i) {

                               }
                           });
                        }

                    }

                    @Override public void mutualFail(int i) {

                    }
                    });

                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityHomeBinding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(activityHomeBinding.getRoot());
        deviceMac = getIntent().getStringExtra("blue_address");
        if (TextUtils.isEmpty(deviceMac)) {
            Toast.makeText(this, getString(R.string.device_address), Toast.LENGTH_SHORT).show();
            return;
        }
        AolonFitManager.getInstance().initSDK(this.getApplicationContext());
        AolonFitManager.getInstance().setHardwareConfigCallBack(new OnCyberDataCallBack<HardwareConfig>() {
            @Override
            public void callBack(HardwareConfig hardwareConfig) {
                Log.e("HomeActivity", "收到功能回调");
                List<String> apiFunction = new ArrayList<>();
                if (hardwareConfig != null) {
                    if (hardwareConfig.isSupportHeartRate()) {
                        apiFunction.add(getString(R.string.heart_rate_monitoring));
                    }
                    if (hardwareConfig.isSupportStress()) {
                        apiFunction.add(getString(R.string.stress_monitoring));
                    }
                    if (hardwareConfig.isSupportAppNotification()) {
                        apiFunction.add(getString(R.string.reminder_operation));
                    }
                    if (hardwareConfig.isSupportSMSNotification()) {
                        apiFunction.add(getString(R.string.sms));
                    }
                    if (hardwareConfig.isSupportWeather()) {
                        apiFunction.add(getString(R.string.weather_information));
                    }
                    if (hardwareConfig.isSupportHeartRateHighWarning()) {
                        apiFunction.add(getString(R.string.max_heart));
                    }
                    if (hardwareConfig.isSupportHeartRateLowWarning()) {
                        apiFunction.add(getString(R.string.min_heart));
                    }
                    if (hardwareConfig.isSupportSedentaryReminder()) {
                        apiFunction.add(getString(R.string.sedentary_monitoring));
                    }
                    if (hardwareConfig.isSupportDrinkReminder()) {
                        apiFunction.add(getString(R.string.water_clock));
                    }
                    if (hardwareConfig.isSupportRaiseLightScreen()) {
                        apiFunction.add(getString(R.string.raise_hand));
                    }
                    if (hardwareConfig.isSupportFindDevice()) {
                        apiFunction.add(getString(R.string.find_watch));
                    }
                    if (hardwareConfig.isSupportTimeFormat()) {
                        apiFunction.add(getString(R.string.sync_time));
                    }
                    if (hardwareConfig.isSupportMetric()) {
                        apiFunction.add(getString(R.string.equipment_unit));
                    }
                    if (hardwareConfig.isSupportNotDisturbMode()) {
                        apiFunction.add(getString(R.string.do_not_disturb));
                    }
                    if (hardwareConfig.isSupportImportContact()) {
                        apiFunction.add(getString(R.string.Add_contact));
                    }
                    if (hardwareConfig.isSupportChangeLanguage()) {
                        apiFunction.add(getString(R.string.language_information));
                    }
                    if (hardwareConfig.isSupportCallReminder()) {
                        apiFunction.add(getString(R.string.incoming_call));
                    }
                    if (hardwareConfig.isSupportSOS()) {
                        apiFunction.add(getString(R.string.sos));
                    }
                    if (hardwareConfig.isSupportWorldClock()) {
                        apiFunction.add(getString(R.string.word_time));
                    }
                    if (hardwareConfig.isSupportAlarmClock()) {
                        apiFunction.add(getString(R.string.alarm_clock));
                    }
                    if (hardwareConfig.isSupportQuickSMSReply()) {
                        apiFunction.add(getString(R.string.reply_message));
                    }
                    if (hardwareConfig.isSupportSetTodayTarget()) {
                        apiFunction.add(getString(R.string.daily_objectives));
                    }
                    if (hardwareConfig.isSupportMenstrualCycle()) {
                        apiFunction.add(getString(R.string.physiological_period));
                    }
                    if (hardwareConfig.isSupportDIYWatchFace()) {
                        apiFunction.add(getString(R.string.custom_watchFace));
                    }
                    if (hardwareConfig.isSupportOnlineWatchFace()) {
                        apiFunction.add(getString(R.string.online_watchFace));
                    }
                    if (hardwareConfig.isSupportAGPS()) {
                        apiFunction.add(getString(R.string.agps));
                    }
                    apiFunction.add(getString(R.string.ota));
                    apiFunction.add(getString(R.string.user_information));
                    apiFunction.add(getString(R.string.power_information));
                    apiFunction.add(getString(R.string.music_info));
                    apiFunction.add(getString(R.string.sync_data));
                    Log.e("HomeActivity", "绘制界面");
                    if (mHandler != null) {
                        Message message = Message.obtain();
                        message.what = 0x00;
                        message.obj = apiFunction;
                        mHandler.sendMessage(message);
                    }


                } else {
                    Log.e("HomeActivity", "功能配置不存在");
                }


            }
        });
        AolonFitManager.getInstance().setOnBLEConnectStateListener(new OnCyberBLEConnectStateListener() {
            @Override
            public void stateChange(int i) {
                Log.e("HomeActivity", "收到连接状态回调");
                Message message = Message.obtain();
                message.what = 0x01;
                message.arg1 = i;
                if (mHandler != null) {
                    mHandler.sendMessage(message);
                }


            }
        });
        if (AolonFitManager.getInstance().isBLEConnect()) {
            activityHomeBinding.connectState.setText(getString(R.string.device_connected));
            isConnected = true;
        } else {
            AolonFitManager.getInstance().connectBLE(deviceMac, "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        AolonFitManager.getInstance().disconnectBLE();
    }

    class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHold> {
        List<String> apiName;

        public ItemAdapter(List<String> apiName) {
            this.apiName = apiName;
        }

        @NonNull
        @Override
        public ItemHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(HomeActivity.this).inflate(R.layout.adapter_home_recyclerview, parent, false);
            return new ItemHold(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull ItemHold holder, int position) {
            if (apiName == null || apiName.isEmpty()) {
                return;
            }
            final String fName = apiName.get(position);
            holder.apiName.setText(fName);

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!isConnected) {
                        Toast.makeText(HomeActivity.this, getString(R.string.device_disconnect), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (getString(R.string.language_information).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, LanguageActivity.class));
                    } else if (getString(R.string.equipment_unit).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, DeviceUnitActivity.class));
                    } else if (getString(R.string.do_not_disturb).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, NoDisturbActivity.class));
                    } else if (getString(R.string.word_time).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, SyncHomeTimeActivity.class));
                    } else if (getString(R.string.daily_objectives).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, DailyObjectivesActivity.class));
                    } else if (getString(R.string.heart_rate_monitoring).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, HeartReteActivity.class));
                    } else if (getString(R.string.sedentary_monitoring).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, SedentaryActivity.class));
                    } else if (getString(R.string.reminder_operation).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, PushInfoActivity.class));
                    } else if (getString(R.string.weather_information).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, WeatherActivity.class));
                    } else if (getString(R.string.alarm_clock).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, AlarmActivity.class));
                    } else if (getString(R.string.Add_contact).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, AddContactActivity.class));
                    } else if (getString(R.string.sos).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, SosContactActivity.class));
                    } else if (getString(R.string.reply_message).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, MsgActivity.class));
                    } else if (getString(R.string.stress_monitoring).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, StressMonitorActivity.class));
                    } else if (getString(R.string.sms).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, SmsActivity.class));
                    } else if (getString(R.string.max_heart).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, MaxHeartActivity.class));
                    } else if (getString(R.string.min_heart).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, MinHeartActivity.class));
                    } else if (getString(R.string.water_clock).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, WaterReminderActivity.class));
                    } else if (getString(R.string.find_watch).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, FindWatchActivity.class));
                    }  else if (getString(R.string.sync_time).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, SyncTimeActivity.class));
                    } else if (getString(R.string.incoming_call).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, CallActivity.class));
                    } else if (getString(R.string.physiological_period).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, PeriodActivity.class));
                    } else if (getString(R.string.custom_watchFace).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, CustomWatchFace.class));
                    } else if (getString(R.string.online_watchFace).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, OnlineDialActivity.class));
                    } else if (getString(R.string.user_information).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, UserInfoActivity.class));
                    } else if (getString(R.string.power_information).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, PowerActivity.class));
                    } else if (getString(R.string.raise_hand).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, BrightScreenActivity.class));
                    } else if (getString(R.string.music_info).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, MusicActivity.class));
                    } else if (getString(R.string.ota).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, OtaActivity.class));
                    } else if (getString(R.string.sync_data).equalsIgnoreCase(fName)) {
                        startActivity(new Intent(HomeActivity.this, SyncMonitorDataActivity.class));

                    } else {
                        Toast.makeText(HomeActivity.this, getString(R.string.unknown), Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }

        @Override
        public int getItemCount() {
            return apiName == null ? 0 : apiName.size();
        }

        class ItemHold extends RecyclerView.ViewHolder {
            TextView apiName;

            public ItemHold(@NonNull View itemView) {
                super(itemView);
                apiName = itemView.findViewById(R.id.api_name);
            }
        }
    }
}
